Popular Searches
Popular Course Categories
Popular Courses

Implementing Push Notifications with Firebase Cloud Messaging

Implementing Push Notifications with Firebase Cloud Messaging

Firebase Integration and Cloud Services

Implementing Push Notifications with Firebase Cloud Messaging (FCM)

Course: Android App Development

Topic: Implementing Push Notifications with Firebase Cloud Messaging

Course Link: Android App Development Course

Demo Link: Register for a Free Course Demo

Academy Website: JustAcademy


1. Introduction to Push Notifications

Push notifications are messages that an application can deliver to a user's device even when the application is not actively open on the screen. Android applications use push notifications to communicate important information, such as new messages, order updates, reminders, account activity, and promotional announcements.

Firebase Cloud Messaging (FCM) is a messaging service from Google Firebase that enables developers to send notifications and data messages to Android devices and other supported platforms. FCM provides the infrastructure for routing messages from a trusted application server or the Firebase console to registered application instances.

For Android development, FCM is commonly integrated with Firebase services, Kotlin or Java code, Android notification channels, and a backend server when automated or personalized messages are required.

Examples of Push Notifications

  • Chat applications: Notify users when a new message arrives.
  • E-commerce applications: Inform users about order confirmation, shipment, and delivery.
  • Learning applications: Remind students about lessons, assignments, or upcoming sessions.
  • Banking applications: Alert users about account activity, subject to appropriate security controls.
  • News applications: Deliver breaking news and selected content updates.

2. Learning Objectives

After completing this topic, learners should be able to:

  • Understand Firebase Cloud Messaging and its architecture.
  • Create a Firebase project and connect it to an Android application.
  • Add the Firebase Messaging SDK to an Android project.
  • Retrieve and manage an FCM registration token.
  • Implement a custom Firebase messaging service.
  • Receive and process notification and data messages.
  • Request notification permission on Android 13 and higher.
  • Create Android notification channels and display local notifications.
  • Test push notifications using the Firebase console.
  • Understand notification security, troubleshooting, and production best practices.

3. What Is Firebase Cloud Messaging?

Firebase Cloud Messaging is a cross-platform messaging solution that allows an application server or an authorized sender to deliver messages to application instances. The Android application uses the Firebase Messaging SDK to register with FCM, receive supported messages, and handle them according to the message type and application state.

Important FCM Components

Component Description
Firebase project Contains the Firebase configuration and associated application services.
Android application The app installed on the user's device that receives messages.
Firebase Messaging SDK Provides APIs for token retrieval and message handling.
FCM registration token An identifier used to target a particular application instance for messaging. It can change over time.
FirebaseMessagingService A service that handles callbacks for incoming messages and token updates.
Application backend A trusted server that can send authorized messages through the supported FCM APIs.
Android notification manager Displays notifications according to system permissions and channel settings.

4. How Firebase Cloud Messaging Works

The basic notification workflow consists of registering the application, obtaining its current FCM token, sending a message, and handling the message on the device.

  1. The developer creates a Firebase project and registers the Android application.
  2. The Firebase configuration is added to the Android project.
  3. The Firebase Messaging SDK registers the application instance with FCM.
  4. The application retrieves its current registration token when required.
  5. A trusted sender submits a notification or data message through FCM.
  6. FCM routes the message to the target application instance or subscribed topic.
  7. Android displays an eligible notification, or the application processes the message in its messaging service.
  8. When the user taps a notification, the application can open the relevant screen or content.

Architecture Overview

Trusted Backend or Firebase Console
                |
                v
       Firebase Cloud Messaging
                |
                v
       Registered Android Device
                |
                v
     FirebaseMessagingService
                |
                v
   Notification or App Data Handling
                |
                v
        Relevant App Screen

Actual delivery and display depend on device connectivity, operating-system restrictions, app state, notification permission, message priority, and other platform conditions. FCM does not guarantee that every message will be delivered immediately.

5. Prerequisites

Before implementing push notifications, make sure the following requirements are satisfied:

  • Android Studio is installed.
  • An Android project is available, preferably using Kotlin.
  • A Firebase account and Firebase project are available.
  • The Android application has a valid package name or application ID.
  • The project uses a compatible Android Gradle Plugin and Firebase SDK configuration.
  • A compatible Android device or emulator is available. FCM Android clients generally require Google Play services.
  • The application has an appropriate notification permission strategy for Android 13 and higher.

6. Step 1: Create a Firebase Project

  1. Open the Firebase Console.
  2. Sign in using a Google account.
  3. Select the option to create a Firebase project.
  4. Enter a project name, such as AndroidPushDemo.
  5. Complete the setup steps and create the project.
  6. Open the project dashboard and choose the Android application option to register an app.
  7. Enter the exact Android package name used by your application.
  8. Download the generated google-services.json configuration file.

The package name registered in Firebase must match the Android application's application ID. If they do not match, Firebase configuration may fail.

7. Step 2: Add Firebase to the Android Project

Place the downloaded google-services.json file in the app module directory, typically:

YourProject/
  app/
    google-services.json
    src/
      main/
        AndroidManifest.xml

Configure the Google Services Gradle plugin according to the current Firebase Android setup instructions and the project's Gradle version. Plugin versions and dependency versions should be compatible with the project's existing configuration.

Official setup guide: Add Firebase to your Android project.

8. Step 3: Add the Firebase Messaging Dependency

In the app module's build.gradle.kts file, add the Firebase Messaging library. The example uses the Firebase Android BoM to manage compatible Firebase library versions.

dependencies {
    implementation(platform("com.google.firebase:firebase-bom:CURRENT_BOM_VERSION"))
    implementation("com.google.firebase:firebase-messaging")
}

Replace CURRENT_BOM_VERSION with the current stable Firebase Android BoM version recommended by the official setup guide. Do not copy the placeholder literally. If your project uses Groovy Gradle files, use the corresponding Groovy syntax.

Sync the project after making the changes. If the project already uses the Firebase BoM, add only the missing Messaging dependency instead of adding another BoM declaration.

9. Step 4: Configure the Android Manifest

FCM requires a messaging service when the application needs to handle messages in the foreground, process data payloads, or perform custom message handling.

Register the service inside the <application> element of AndroidManifest.xml:

<application
    ...>

    <service
        android:name=".MyFirebaseMessagingService"
        android:exported="false">
        <intent-filter>
            <action android:name="com.google.firebase.MESSAGING_EVENT" />
        </intent-filter>
    </service>

</application>

Make sure the service class name matches its actual package and location. If the class is in a different package, use the appropriate fully qualified name.

10. Step 5: Create FirebaseMessagingService

Create a Kotlin class named MyFirebaseMessagingService.kt. Extend FirebaseMessagingService and override its callbacks to process incoming messages and token updates.

package com.example.androidpushdemo

import android.util.Log
import com.google.firebase.messaging.FirebaseMessagingService
import com.google.firebase.messaging.RemoteMessage

class MyFirebaseMessagingService : FirebaseMessagingService() {

    override fun onMessageReceived(message: RemoteMessage) {
        super.onMessageReceived(message)

        Log.d("FCM", "From: ${message.from}")

        message.notification?.let { notification ->
            Log.d("FCM", "Title: ${notification.title}")
            Log.d("FCM", "Body: ${notification.body}")
        }

        if (message.data.isNotEmpty()) {
            Log.d("FCM", "Data payload: ${message.data}")
        }
    }

    override fun onNewToken(token: String) {
        super.onNewToken(token)

        Log.d("FCM", "New registration token received")

        // Send the updated token to your trusted backend
        // if your application uses server-side targeting.
    }
}

Replace the sample package declaration with the package used by your project. Avoid logging complete registration tokens in production because they are sensitive routing identifiers.

Understanding onMessageReceived()

The onMessageReceived() callback is used for custom handling of messages delivered to the application service. It is especially important for foreground notifications and data payloads. Do not assume that every background notification will invoke this callback in the same way: background notification messages are often displayed directly by the Android FCM SDK.

Understanding onNewToken()

The onNewToken() callback is invoked when the FCM registration token is generated or refreshed. An application that maintains a backend token registry should update its server-side record when this callback occurs.

11. Step 6: Retrieve the FCM Registration Token

The registration token identifies an application instance for FCM messaging. Retrieve the current token when needed and keep it synchronized with your backend if you send targeted notifications.

import android.util.Log
import com.google.firebase.messaging.FirebaseMessaging

private fun fetchFcmToken() {
    FirebaseMessaging.getInstance().token
        .addOnCompleteListener { task ->
            if (!task.isSuccessful) {
                Log.e("FCM", "Unable to retrieve FCM token", task.exception)
                return@addOnCompleteListener
            }

            val token = task.result

            // Send the token to your trusted backend if required.
            // Avoid printing the full token in production logs.
            Log.d("FCM", "FCM token retrieved successfully")
        }
}

You can call this function from an appropriate point in your app's initialization flow. If token registration is linked to a signed-in user, update the backend mapping when the user signs in, signs out, or changes accounts.

Important Token Management Rules

  • Tokens can change, so handle onNewToken().
  • Associate tokens with the correct application installation and, where appropriate, authenticated user.
  • Remove or disassociate stale tokens when appropriate.
  • Do not treat an FCM token as proof that a user is authenticated.
  • Do not expose tokens in public logs, screenshots, or analytics events.

12. Step 7: Request Notification Permission on Android 13+

Android 13, API level 33, introduced the runtime POST_NOTIFICATIONS permission for ordinary app notifications. A message may reach the device while the application is not permitted to display a visible notification. Explain the benefit to the user and request permission at an appropriate point in the application flow.

With compatible Firebase Messaging SDK versions, the permission may already be included through the SDK's manifest configuration. Verify your merged manifest and request the runtime permission in your application.

import android.Manifest
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat

class MainActivity : AppCompatActivity() {

    private val notificationPermissionLauncher =
        registerForActivityResult(
            ActivityResultContracts.RequestPermission()
        ) { isGranted ->
            if (isGranted) {
                // Notifications can be displayed subject
                // to other device and channel settings.
            } else {
                // Keep the app usable without notifications.
            }
        }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        requestNotificationPermissionIfNeeded()
    }

    private fun requestNotificationPermissionIfNeeded() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            val permission = Manifest.permission.POST_NOTIFICATIONS

            if (ContextCompat.checkSelfPermission(
                    this,
                    permission
                ) != PackageManager.PERMISSION_GRANTED
            ) {
                notificationPermissionLauncher.launch(permission)
            }
        }
    }
}

This example demonstrates the permission request flow. In a production application, consider showing a brief explanation before requesting permission and choose a context in which notifications provide clear value. Do not repeatedly interrupt users who have declined.

13. Step 8: Create a Notification Channel

Android 8.0, API level 26, and later versions use notification channels. A channel lets users control the behavior of a category of notifications, such as general updates, chat messages, or order alerts.

Create a channel before displaying custom notifications:

import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.Context
import android.os.Build

fun createNotificationChannel(context: Context) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        val channel = NotificationChannel(
            "general_updates",
            "General Updates",
            NotificationManager.IMPORTANCE_DEFAULT
        ).apply {
            description = "Notifications about important app updates"
        }

        val manager = context.getSystemService(
            Context.NOTIFICATION_SERVICE
        ) as NotificationManager

        manager.createNotificationChannel(channel)
    }
}

Call createNotificationChannel(this) from an appropriate initialization point, such as the activity's onCreate() method. Creating a channel more than once with the same ID is safe; Android retains user-controlled channel settings.

14. Step 9: Display a Custom Notification

When the app needs to show a notification itself, use Android's notification APIs. This is useful for foreground messages, data messages, and custom notification behavior.

import android.Manifest
import android.app.NotificationManager
import android.content.Context
import android.content.pm.PackageManager
import android.os.Build
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import androidx.core.content.ContextCompat

fun showLocalNotification(
    context: Context,
    title: String,
    body: String
) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
        if (ContextCompat.checkSelfPermission(
                context,
                Manifest.permission.POST_NOTIFICATIONS
            ) != PackageManager.PERMISSION_GRANTED
        ) {
            return
        }
    }

    val notification = NotificationCompat.Builder(
        context,
        "general_updates"
    )
        .setSmallIcon(R.drawable.ic_notification)
        .setContentTitle(title)
        .setContentText(body)
        .setStyle(
            NotificationCompat.BigTextStyle().bigText(body)
        )
        .setPriority(NotificationCompat.PRIORITY_DEFAULT)
        .setAutoCancel(true)
        .build()

    NotificationManagerCompat.from(context)
        .notify(1001, notification)
}

Replace R.drawable.ic_notification with a valid small notification icon in your project. Add the AndroidX Core dependency if it is not already available. The example checks notification permission on Android 13 and higher; other device settings, such as channel settings, can still affect whether a notification appears.

15. Step 10: Process Incoming Messages

Connect the service callback to your notification function when you want to display a custom notification for messages delivered to the service.

override fun onMessageReceived(message: RemoteMessage) {
    super.onMessageReceived(message)

    val title = message.notification?.title
        ?: message.data["title"]
        ?: "New Update"

    val body = message.notification?.body
        ?: message.data["body"]
        ?: "You have a new notification."

    showLocalNotification(
        applicationContext,
        title,
        body
    )
}

For this example, the showLocalNotification() function must be accessible from the service class or a shared notification helper. Make sure the application does not create duplicate notifications when the FCM SDK is already displaying a background notification message.

16. Notification Messages vs. Data Messages

FCM supports notification payloads, data payloads, and combinations of the two. The message type influences how Android handles the message depending on whether the app is in the foreground or background.

Message Type Purpose Typical Handling
Notification message Displays a title and message body to the user. When the app is in the background, the FCM SDK commonly displays it automatically. Foreground handling can be customized.
Data message Delivers application-defined key-value data. The service processes delivered data and decides what action is appropriate.
Combined message Includes notification fields and custom data. Behavior varies by app state; background notification display and data handling must be designed carefully.

Example Data Payload

{
  "message": {
    "token": "TARGET_FCM_REGISTRATION_TOKEN",
    "data": {
      "title": "Order Update",
      "body": "Your order has been shipped.",
      "orderId": "ORD-2048",
      "screen": "order_details"
    }
  }
}

This is an illustrative payload shape for the FCM HTTP v1 API. The placeholder token must be replaced with a valid target token, and a trusted backend must authenticate and send the request. Never place service-account credentials or server authorization secrets inside an Android application.

17. Step 11: Send a Test Notification from Firebase Console

Firebase Console is a convenient way to test basic notification delivery before implementing a complete backend messaging system.

  1. Install and run the Android application on a compatible device.
  2. Make sure Firebase is correctly configured and the application has initialized.
  3. Retrieve the current FCM registration token using the SDK.
  4. Open the Firebase Console and select your project.
  5. Navigate to the Messaging or Notifications composer. The exact menu names may vary.
  6. Create a notification with a title and message body.
  7. Choose the test-message option if available.
  8. Enter the target application's current FCM registration token.
  9. Send the test message and observe the device.
  10. Repeat the test with the application in the foreground and background.

For the official walkthrough, visit Get started with Firebase Cloud Messaging for Android.

18. Step 12: Send Notifications from a Trusted Backend

For real applications, notifications are commonly sent from a trusted backend when an event occurs, such as a new chat message, a payment update, or a shipment status change.

The backend should use the Firebase Cloud Messaging HTTP v1 API or an appropriate Firebase Admin SDK. It must authenticate securely and determine which registered application instances should receive each message.

Recommended Backend Workflow

  1. Authenticate the user and validate the event that should trigger a notification.
  2. Look up the current registered device token or topic subscription.
  3. Build a message containing only the data needed by the client.
  4. Send the message through an authorized server-side FCM integration.
  5. Inspect the response and handle invalid or stale registration tokens.
  6. Record appropriate delivery or processing status without storing unnecessary sensitive content.

Official server-side documentation: Send messages using the FCM HTTP v1 API.

Security warning: Never embed service-account private keys, server credentials, or privileged FCM authorization secrets in an APK. Client applications are not trusted environments for server credentials.

19. Step 13: Subscribe to Notification Topics

Topics allow an application to receive messages intended for a group of subscribers, such as users interested in product announcements or course updates.

import android.util.Log
import com.google.firebase.messaging.FirebaseMessaging

fun subscribeToTopic() {
    FirebaseMessaging.getInstance()
        .subscribeToTopic("course_updates")
        .addOnCompleteListener { task ->
            if (task.isSuccessful) {
                Log.d("FCM", "Topic subscription successful")
            } else {
                Log.e("FCM", "Topic subscription failed", task.exception)
            }
        }
}

fun unsubscribeFromTopic() {
    FirebaseMessaging.getInstance()
        .unsubscribeFromTopic("course_updates")
        .addOnCompleteListener { task ->
            if (!task.isSuccessful) {
                Log.e("FCM", "Topic unsubscribe failed", task.exception)
            }
        }
}

Topic names should be meaningful and consistent. Do not use a public topic as an authorization mechanism for private information. If a notification contains personal or account-specific data, use an appropriately secured server-side targeting strategy.

20. Step 14: Handle Notification Taps

Notifications often need to open a specific screen when the user taps them. For example, an order notification can open an order-details screen, while a chat notification can open the relevant conversation.

Use a PendingIntent with an explicit destination and carefully validated navigation data. A simplified example is shown below:

import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import androidx.core.app.NotificationCompat

fun buildNotification(
    context: Context,
    title: String,
    body: String
) {
    val intent = Intent(context, MainActivity::class.java).apply {
        flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or
            Intent.FLAG_ACTIVITY_SINGLE_TOP
    }

    val pendingIntent = PendingIntent.getActivity(
        context,
        0,
        intent,
        PendingIntent.FLAG_UPDATE_CURRENT or
            PendingIntent.FLAG_IMMUTABLE
    )

    val notification = NotificationCompat.Builder(
        context,
        "general_updates"
    )
        .setSmallIcon(R.drawable.ic_notification)
        .setContentTitle(title)
        .setContentText(body)
        .setContentIntent(pendingIntent)
        .setAutoCancel(true)
        .build()

    // Check notification permission where required,
    // then post the notification through NotificationManagerCompat.
}

This snippet demonstrates the tap-action setup; connect it to the notification display function and permission checks shown earlier. In a larger app, use the navigation architecture already adopted by the project and validate all incoming identifiers before loading protected content.

21. Foreground and Background Notification Behavior

Notification handling depends on both the payload type and the application's state.

App State Notification Payload Data Payload
Foreground The app can handle the message in onMessageReceived() and display a custom notification if appropriate. The service can process delivered data and perform suitable application logic.
Background The FCM SDK commonly displays the notification automatically. The service can process data messages when delivered, subject to platform limits and message priority.
Terminated or restricted Delivery and visible display depend on system conditions and the message configuration. Do not assume immediate execution or unlimited background processing.

For longer processing tasks, do not rely on keeping onMessageReceived() running for an extended period. Schedule appropriate work, for example through WorkManager, when the task must continue beyond the short message-handling window.

22. Common Errors and Troubleshooting

Problem Possible Cause Solution
No notification appears Notification permission is denied or notifications are disabled. Check runtime permission, system notification settings, and channel settings.
Firebase configuration error Incorrect package name or misplaced configuration file. Verify the Firebase app registration and place google-services.json in the app module.
Token retrieval fails Network issue, Firebase setup issue, or unavailable Google Play services. Check the error details, internet connectivity, SDK setup, and device compatibility.
Background notification is not processed by custom code Notification payloads can be displayed automatically when the app is in the background. Understand payload-specific behavior and use data messages when custom handling is required.
Custom notification crashes Missing small icon, invalid channel ID, or incorrect notification setup. Use a valid icon resource, create the channel, and review Logcat output.
Old token no longer works The registration token may have changed or become invalid. Refresh the token and maintain the backend's token registry.
Duplicate notifications appear The app displays a local notification while FCM also displays the background notification. Separate automatic notification display from custom foreground/data handling.
Notification tap opens the wrong screen PendingIntent identity or navigation extras are not configured correctly. Use explicit intents, appropriate request codes, and validated destination data.
Messages are delayed Device connectivity, battery restrictions, priority, or system delivery conditions. Check device state and message design; do not assume every message is immediate.

23. Best Practices for Firebase Push Notifications

  • Ask permission responsibly: Explain the value of notifications before requesting permission on Android 13 and higher.
  • Keep messages relevant: Avoid excessive or repetitive notifications.
  • Manage tokens correctly: Update server-side registrations when tokens change and remove stale records.
  • Protect private information: Avoid including sensitive account or payment information in notification text.
  • Secure sending credentials: Send messages from a trusted backend, not directly from client-side application code using privileged credentials.
  • Use notification channels: Separate important categories and respect the user's channel preferences.
  • Design for every app state: Test foreground, background, and terminated or restricted states.
  • Handle errors: Log useful diagnostic details without exposing complete tokens or private message content.
  • Keep payloads small: Send only the data needed to identify the event or navigate to the relevant screen.
  • Validate notification actions: Verify identifiers and permissions before opening protected application content.
  • Use the right delivery strategy: Topics work for broad updates; user-specific messages generally require carefully managed registration records.
  • Respect Android background limits: Use appropriate background work APIs for tasks that take longer than message processing should.

24. Practical Project: Android Push Notification App

Build a small Android application that receives course announcements using Firebase Cloud Messaging.

Project Requirements

  • Connect the Android app to Firebase.
  • Add the Firebase Messaging dependency.
  • Register MyFirebaseMessagingService in the manifest.
  • Retrieve the current FCM token for testing.
  • Request notification permission on Android 13 and higher.
  • Create a notification channel.
  • Handle foreground notifications and data messages.
  • Test background notification display through the Firebase console.
  • Open a relevant app screen when the notification is tapped.
  • Document common failures and the steps used to resolve them.

Suggested Project Structure

app/
  src/main/
    java/com/example/androidpushdemo/
      MainActivity.kt
      MyFirebaseMessagingService.kt
      NotificationHelper.kt
    res/
      drawable/
        ic_notification.xml
    AndroidManifest.xml
  google-services.json

The structure is illustrative. Adapt package names and resource locations to your actual project. Keep notification creation in a helper class if that makes the service easier to maintain and test.

Testing Checklist

  • Firebase configuration is valid.
  • The app starts without Firebase initialization errors.
  • A current registration token can be retrieved.
  • The user can grant or deny notification permission.
  • A test notification is received while the app is in the background.
  • Foreground message handling works as intended.
  • Data payload values are processed safely.
  • Notification taps open the expected destination.
  • Token refreshes are handled by the application.
  • The application remains usable when notifications are disabled.

25. Practice Exercises

  1. Create a Firebase project and connect it to an Android application.
  2. Implement a Firebase messaging service in Kotlin.
  3. Retrieve the FCM token and explain why it can change.
  4. Request notification permission on Android 13 and higher.
  5. Create a notification channel named course_updates.
  6. Display a custom notification with a title, body, and small icon.
  7. Send a test notification from the Firebase console.
  8. Compare notification payloads with data payloads in foreground and background states.
  9. Implement topic subscription for general course announcements.
  10. Design a secure backend workflow for sending personalized notifications.

26. Interview Questions and Answers

Q1. What is Firebase Cloud Messaging?

Answer: Firebase Cloud Messaging is a service that allows developers to send messages and notifications to registered application instances across supported platforms.

Q2. What is an FCM registration token?

Answer: It is a token used to target a particular application instance for messaging. It can change, so applications that use backend targeting must maintain current registration information.

Q3. What is FirebaseMessagingService?

Answer: It is an Android service provided by the Firebase Messaging SDK. Developers extend it to handle callbacks such as incoming messages and registration token updates.

Q4. What is the purpose of onMessageReceived()?

Answer: It provides a callback for processing messages delivered to the service. It is commonly used for foreground message handling and data payload processing.

Q5. What is the purpose of onNewToken()?

Answer: It notifies the application that an FCM registration token has been generated or refreshed, allowing the application to synchronize its registration with a backend.

Q6. What is the difference between notification and data messages?

Answer: Notification messages include user-facing notification content, while data messages contain application-defined key-value pairs. Background notification messages are commonly displayed automatically, whereas data messages are intended for application processing when delivered.

Q7. Why are notification channels important?

Answer: Notification channels categorize notifications on Android 8.0 and higher and let users control notification behavior for each category.

Q8. Why does Android 13 require notification permission?

Answer: Android 13 introduced the POST_NOTIFICATIONS runtime permission for ordinary app notifications. Apps need the user's permission to display them.

Q9. Can notifications be sent directly from an Android client using server credentials?

Answer: No. Privileged server credentials must remain on a trusted backend. The client should not contain service-account private keys or other privileged sending credentials.

Q10. What are FCM topics?

Answer: Topics group application instances that want to receive a category of messages. They are useful for broad announcements but should not be treated as access control for private data.

Q11. Why might a notification not appear even if a message was sent?

Answer: Possible causes include denied notification permission, disabled channel settings, incorrect Firebase configuration, invalid tokens, device connectivity, or operating-system delivery restrictions.

Q12. What should an application do when an FCM token changes?

Answer: It should update the associated registration in its trusted backend and remove obsolete registrations when appropriate.

27. Quick Revision

  • FCM is used to send messages to registered application instances.
  • The Firebase Messaging SDK provides Android messaging APIs.
  • FirebaseMessagingService handles custom message callbacks.
  • onNewToken() supports token refresh handling.
  • Notification payload behavior differs from data payload behavior.
  • Android 8.0 and higher use notification channels.
  • Android 13 and higher require runtime permission for ordinary notifications.
  • The Firebase console is useful for testing simple notification delivery.
  • Trusted backends should send authorized production messages.
  • Registration tokens and user data must be handled securely.

28. Official Learning Resources

29. Conclusion

Firebase Cloud Messaging is an important tool for building interactive Android applications. By connecting an Android project to Firebase, implementing FirebaseMessagingService, managing registration tokens, requesting notification permission, and creating notification channels, developers can build a reliable foundation for push notifications.

For production applications, notification delivery should be paired with secure backend messaging, token lifecycle management, careful handling of personal information, and testing across app states and Android versions. These practices help create notifications that are useful, secure, and respectful of user preferences.

To explore structured Android development training, visit JustAcademy's Android App Development Course, register for a course demo, or browse the JustAcademy website.

Previous Next
whatsapp